'''
This script check out the parameters of a ppf file and an eqt file into the database
Usage:
    checkout.py dbname tablename version output.ppf [file or folder] 
For Example:
    checkout.py mydatabase.dffdb AMBER1 3 result.ppf
        It check out all parameters (version <=3) into result.ppf and 
        result.eqt in the table AMBER1 in mydatabase.dffdb
    checkout.py mydatabase.dffdb AMBER1 3 result.ppf MyMol.msd
        It check out all required parameters of MyMol.msd (version <=3) 
        into result.ppf and result.eqt in the table AMBER1 in mydatabase.dffdb
    checkout.py mydatabase.dffdb AMBER1 3 result.ppf required.ppf
        It check out all the items (version <=3) in required.ppf into 
        result.ppf and result.eqt in the table AMBER1 in mydatabase.dffdb
    checkout.py mydatabase.dffdb AMBER1 latest result.ppf Data
        if the Data is a folder with msd file in it.  It check out all required
        parameters (latest version) into result.ppf and result.eqt
       
Created on 2009-8-26

@author: madlee
'''

import kuai

REQUIRED_TERM = ["ATC", "BINC", "N12_6", "BHARM", "AHARM", "TCOSP", "IBCOS"]

if __name__ == '__main__':
    from sys import argv
    if len(argv) != 5 and len(argv) != 6:
        print __doc__
    else:
        from kuai.dff.dffdb import Database
        db = Database(argv[1], argv[2])    
        if argv[3] == 'latest':
            version = None
        else:
            version = int(argv[3])
        if len(argv) == 5:
            db.export(argv[4], version)
        else:
            assert len(argv) == 6
            import os.path
            if argv[5].endswith('.ppf'):
                ff, eqt = kuai.read_ff(argv[5])
            elif argv[5].endswith('.msd'):
                mol = kuai.read_mol(argv[5])
                ff = kuai.ForceField.list_keys(mol, REQUIRED_TERM)
            elif os.path.isdir(argv[5]):
                folder = argv[5]
                from sets import Set
                ff = Set()
                for file in os.listdir(folder):
                    if file.endswith('.msd'):
                        mol = kuai.read_mol(os.path.join(folder, file))
                        keys = kuai.ForceField.list_keys(mol, REQUIRED_TERM)
                        ff = required.union(set(keys))
            else:
                raise ValueError("Unknow the meaning of %s" % argv[5])
            ff, eqt = db.checkout(required, version)
            file = open(argv[4], 'wt')
            file.write(str(ff))
            file.close()
            
            file = open(kuai.EquivalenceTable.get_eqt_filename(argv[4]), 'wt')
            file.write(str(eqt))
            file.close()
        print "The contents of %s in %s were saved into %s" % (argv[2], argv[1], argv[4])
            
            
                